Vue.use(httpVueLoader);
Vue.use(AsyncComputed);
Vue.use(VueRouter);
Vue.use(ELEMENT);

// 修改原型对象中的push方法，因为kv.vue中每次变更query都被vue认为是一次重复路由抛出异常，这里是为了去掉异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

require.config({ paths: { 'vs': './js/monaco-editor/vs' } });
require.config({ 'vs/nls': { availableLanguages: { '*': 'zh-cn' } } });
const service = `${ window.location.protocol }//${ window.location.host }/sso/login`;

require(['vs/editor/editor.main'], function () {
  const routes = [
    { path: '/kv', component: httpVueLoader('./js/component/kv.vue') },
    { path: '/create-kv', component: httpVueLoader('./js/component/create-kv.vue') },
    { path: '/checker', component: httpVueLoader('./js/component/checker.vue') },
    { path: '/validate', component: httpVueLoader('./js/component/validate.vue') },
    { path: '/checker-validate', component: httpVueLoader('./js/component/checker-validate.vue') },
    { path: '/user', component: httpVueLoader('./js/component/user.vue') },
  ];

  const router = new VueRouter({ routes });
  window.app = new Vue({
    el: '#app',
    router,
    data: {
      dc: 'm7',
      name: '',
    },
    methods: {
      onSelect() {
        this.$refs.dcList.style.display = 'none';
        document.removeEventListener('click', this.onSelect);
      },
      changeDc() {
        this.$refs.dcList.style.display = '';
        document.addEventListener('click', this.onSelect);
      },
      selectDc(event) {
        this.dc = event.target.innerText;
        // 更新路由
        this.$router.push({ path: '/kv', query: { ...this.$route.query, dc: this.dc } });
        this.onSelect();
      },
      async logout() {
        await this.$confirm('确定退出吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await axios.get('/sso/logout');
        window.location = `https://sso.oaloft.com/cas/logout?service=${ encodeURIComponent(service) }`;
      }
    },
  });

  axios.interceptors.response.use(function (response) {
    const { data } = response;
    if (!data.success) {
      window.app.$message.error(data.message);
    }
    return response;
  }, function (error) {
    const { status } = error.response;
    if (status === 401) {
      window.location = `https://sso.oaloft.com/cas/logout?service=${ encodeURIComponent(service) }`;
      return error;
    }
  });

  axios.get('/sso/get-user-info').then(({ data }) => {
    if (!data.info) {
      window.location = `https://sso.oaloft.com/cas/logout?service=${ encodeURIComponent(service) }`;
      return;
    }
    window.app.name = data.info.name;
  });
});